<?php
namespace app\index\controller;
use think\Controller;
use think\Db;
use think\Loader;
use think\Cache;
class WxPay extends Controller
{
    
    public function _empty($name)
    {
        return $this->fetch('/Public/404');
    }
    
    public function __construct(){
        parent::__construct();
        require_once ROOT_PATH."extend/php_sdk_v3.0.10/lib/WxPay.Api.php";
        require_once ROOT_PATH."extend/php_sdk_v3.0.10/example/WxPay.JsApiPay.php";
        require_once ROOT_PATH."extend/php_sdk_v3.0.10/example/log.php";
        // require_once ROOT_PATH."extend/php_sdk_v3.0.10/lib/WxPay.Notify.php";
    }
    
    
   
    
    public function wxnewpay(){
        //  $logHandler= new \CLogFileHandler;
        //  $log = \Log::Init($logHandler, 15);
           if(!is_weixin()){
                $this->redirect("https://xw.qq.com/");
            }
     
            global $content;
          
            $code    = input("code");
    
    		$state   = input("state");
    		
    		
    	
    		if(empty($code)){
    		     die('缺少参数code,支付配置错误');
    		}
    		
    		if(empty($state)){
    		     die('缺少参数订单号');
    		}
		
	    	$order_info = Cache::store('redis')->get($state);

            
            $out           = $order_info['orderid'];
            $total_fee     = $order_info['money']*100;
            $codehou       = $order_info['code'];
            $userid        = $order_info['userid'];
            $ddh3          = $order_info['ddh3'];
            $uopenid       = $order_info['uopenid'];
            $zyid          = $order_info['zyid'];
            $zftd          = $order_info['zftd'];
            
            
            // $is_gongzhong = Db::name('uopenid')->where(['uopenid' => $uopenid])->find();
            
            // if($is_gongzhong){
            //      die('请重新支付');
            // }
            
            
            $ts     = check_ts("",$uopenid,"");
            if($ts){
                // $ename = Db::name('ename')->where(['status' => 1, 'zt' => 1,'type' => 3])->value('ename');
                // $longurl = "http://".$ename ."/index/pay/saoma.html?userid=" . $order_info['jiami'] . '&zyid=' . $zyid . "&code=" . $order_info['jiami']."&uopenid=".$uopenid. '&money=' . $order_info['money']."&ddh=".$ddh3;
                // header('Location:'.$longurl);
                // exit;
                $saomatype = Db::name('config')->where(['name' => 'saomatype'])->value('value');//强制扫码切换  
                $ename = Db::name('ename')->where(['status' => 1, 'zt' => 1,'type' => 3])->value('ename');
                // 1:七七扫码2:喜乐付扫码3:麒麟扫码
                if($saomatype == 1)
                {
                      if($order_info['money'] >= 30){
                           $longurl = "http://".$ename ."/index/fang/dalaohu.html?userid=" . $order_info['jiami'] . '&zyid=' . $zyid . "&code=" . $order_info['jiami']."&uopenid=".$uopenid. '&money=' . $order_info['money']."&ddh=".$ddh3."&is_baotian=1"."&b_money=".$order_info['money'];
                      }else{
                           $longurl = "http://".$ename ."/index/fang/dalaohu.html?userid=" . $order_info['jiami'] . '&zyid=' . $zyid . "&code=" . $order_info['jiami']."&uopenid=".$uopenid. '&money=' . $order_info['money']."&ddh=".$ddh3;
                      }
                   
                }elseif($saomatype == 2)
                {
                    if($order_info['money'] >= 30){
                         $longurl = "http://".$ename ."/index/fang/index.html?userid=" . $order_info['jiami'] . '&zyid=' . $zyid . "&code=" . $order_info['jiami']."&uopenid=".$uopenid. '&money=' . $order_info['money']."&ddh=".$ddh3."&is_baotian=1"."&b_money=".$order_info['money'];
                    }else{
                         $longurl = "http://".$ename ."/index/fang/index.html?userid=" . $order_info['jiami'] . '&zyid=' . $zyid . "&code=" . $order_info['jiami']."&uopenid=".$uopenid. '&money=' . $order_info['money']."&ddh=".$ddh3;
                    }
                    
                  
                }else{
                    die('支付忘记开了,请联系管理员!!!');
                }
                header('Location:'.$longurl);
                exit;
            }
            

            $zhifu = Db::name("zhifu")->where(['id' => $order_info['zftd']])->find();
            
            
            $content = unserialize($zhifu['content']);
            
            $xieyi = "http://";
            $body = "test";
            // $good = array("舒肤佳肥皂2盒装","香皂bai香味持久","男士洗面奶深层清洁","创意夜间照明灯","du搓澡巾清洁","沐浴zhi露持久留香","海飞丝洗发露","梳子","立体两面dao镜子","无味无添加卫生纸","洗zhuan衣粉持久留香","公牛插板1米装","卡通版儿童版雨伞","ins大理石陶瓷杯马克杯子","创意马卡龙儿童3只装牙刷卡通软毛糖果色日系两","304双层不锈钢真空保温杯直身商务水杯子","萃汇尔水性可剥可撕拉指甲油8ml","粉底调色盘美甲用品方形指环","欧丽丝免烤微胶指甲油 3瓶套装","俏夫人大号纸卡装精钢指甲剪刀家居","创意陶瓷卡通马克杯子学生大容量猫咪水杯","跳棋益智玻璃珠飞行棋子","儿童凳子笑脸卡通塑料小凳子 地摊小板凳","20支笔20支笔芯中性笔套装","韩国马卡龙牙刷10支装家用软毛牙刷地摊爆款","双面面板 家用厨房揉面 蒸馒头 多用 砧板","家用扫把簸箕组合套装 家庭清洁用品","1500ml水杯夏季冷水用杯","粮果色不锈钢拉丝修甲六件套","汤勺漏勺不锈钢厨具家用火锅汤勺","时尚化妆镜 PU皮双面镜","双头细轴纸棒棉签棉棒","JGJ喷漆工艺蓝色修甲指甲刀18件套");
            
            $good = array("美点双辉映","合欢水果盘","凤凰展彩堂","扬州炒饭","香肠炒饭","西红柿炒饭","咖喱炒饭","培根炒饭","扬州炒饭","西班牙海鲜饭","意大利海鲜饭","西式蟹肉炒饭","正宗日式咖喱鸡饭","蔬果炒饭","番茄咖喱炒饭","腊肠炒饭","海鲜炒饭","咸蛋黄炒饭","泡菜炒饭","要角炒饭","咸鱼鸡粒炒饭","翡翠炒饭","蟹肉生菜炒饭","绿豆薏仁炒饭","绿豆薏仁炒饭","绿豆薏仁炒","番茄炒饭","香蕉炒饭","鸡汁炒饭","广式叉烧炒饭","孜然牛肉炒饭","春色炒饭","土豆培根炒饭","香菇炒饭","菠萝虾仁炒饭","酱油炒饭","鸡蛋芹菜炒饭","肉丝炒饭");
            $key = array_rand($good,1);
            $body = $good[$key];
            
            
            try{
                $total_fee = intval($total_fee);
                // $total_fee = "1";
            	$tools = new \JsApiPay();
            	$openId = $tools->GetOpenid();
            	//②、统一下单
            	$input = new \WxPayUnifiedOrder();
            	$input->SetBody("$body");
            	$input->SetAttach("$zftd");
            	$input->SetOut_trade_no("$out");
            	$input->SetTotal_fee($total_fee); 
            	$input->SetTime_start(date("YmdHis"));
            	$input->SetTime_expire(date("YmdHis", time() + 600));
            	$input->SetGoods_tag("test");
            	$input->SetNotify_url($xieyi . $content['shename'].url('wxhuidiao'));
            	$input->SetTrade_type("JSAPI");
            	$input->SetOpenid($openId);
                $config = new \WxPayConfig();
                $order = \WxPayApi::unifiedOrder($config, $input);
                $jsApiParameters = $tools->GetJsApiParameters($order);
                // 	//获取共享收货地址js函数参数
                // 	$editAddress = $tools->GetEditAddressParameters();
            	$this->assign("jsApiParameters", $jsApiParameters);
           
     
                $ename = Cache::store('redis')->get('ylluodi');
        
        
                $tzurl  = "http://" . $ename."/index/index/hezi/?userid=".$order_info['jiami']."&ddh=".$ddh3."&uopenid=".$uopenid;
                $tzurls  = "http://" . $ename."/index/index/shipinok/?zyid=".$zyid."&ddh=".$out."&uopenid=".$uopenid;
              
                $this->assign("userid", $userid);
                
                $this->assign("tzurls", $tzurls);
                $this->assign("tzurl", $tzurl);
                
                return $this->fetch();
            } catch(\Exception $e) {
               
                $saomatype = Db::name('config')->where(['name' => 'saomatype'])->value('value');//强制扫码切换  
                $ename = Db::name('ename')->where(['status' => 1, 'zt' => 1,'type' => 3])->value('ename');
                // 1:七七扫码2:喜乐付扫码3:麒麟扫码
                if($saomatype == 1)
                {
                    $longurl = "http://".$ename ."/index/pay/saoma.html?userid=" . $order_info['jiami'] . '&zyid=' . $zyid . "&code=" . $order_info['jiami']."&uopenid=".$uopenid. '&money=' . $order_info['money']."&ddh=".$ddh3;
                }elseif($saomatype == 2)
                {
                   $longurl = "http://".$ename ."/index/fang/index.html?userid=" . $order_info['jiami'] . '&zyid=' . $zyid . "&code=" . $order_info['jiami']."&uopenid=".$uopenid. '&money=' . $order_info['money']."&ddh=".$ddh3;
                }elseif($saomatype == 3)
                {
                    // die('还未开通支付,请联系管理员!!!');
                    $longurl = "http://".$ename ."/index/pay/qlpay.html?userid=" . $order_info['jiami'] . '&zyid=' . $zyid . "&code=" . $order_info['jiami']."&uopenid=".$uopenid. '&money=' . $order_info['money']."&ddh=".$ddh3;
                    // $longurl = "http://".$ename ."/index/pay/saoma.html?userid=" . $order_info['jiami'] . '&zyid=' . $zyid . "&code=" . $order_info['jiami']."&uopenid=".$uopenid. '&money=' . $order_info['money']."&ddh=".$ddh3;
                }else{
                    die('支付忘记开了,请联系管理员!!!');
                }
                header('Location:'.$longurl);
                exit;
            }
    }
    
    
    
    
    
  
     public function wxhuidiao()
    {
        global $content;
       
        Loader::import('com.wxpay.WxPayPubHelper');
        $notify = new \Notify_pub();
        $xml = file_get_contents('php://input');
        
        $notify->saveData($xml);
        
      
        $zhifu = Db::name("zhifu")->where(['id' => 1])->find();
        $content = unserialize($zhifu['content']);
        
        
        
        if ($notify->checkSign() == FALSE)
        {
            $notify->setReturnParameter("return_code", "FAIL"); //返回状态码
            $notify->setReturnParameter("return_msg", "签名失败"); //返回信息
        }
        else
        {
            
             $notify->setReturnParameter("return_code", "SUCCESS"); //设置返回码
             $log_name = "wx.log"; //log文件路径
             $returnXml = $notify->returnXml();
             writefile($log_name, "【接收到的notify通知】:\n" . $xml . "\n");
        }
        $returnXml = $notify->returnXml();
        echo $returnXml;
         
        
        if ($notify->checkSign() == TRUE)
        {
            if ($notify->data["return_code"] == "FAIL")
            {
                writefile($log_name, "【通信出错】:\n" . $xml . "\n");
            }elseif ($notify->data["result_code"] == "FAIL")
            {
                writefile($log_name, "【业务出错】:\n" . $xml . "\n");
            }
            else
            {
                $shijian = date('Y-m-d H:i:s' , time());
                $out_trade_no = $notify->data["out_trade_no"]; //
                $weixin = $notify->data["transaction_id"]; //微信订单号
                $cymoney = $notify->data["total_fee"] / 100;
                $orderNo = $notify->data["out_trade_no"]; //我提交的订单号
                $openid  = $notify->data["openid"];//微信openid
                
                $order = Cache::store('redis')->get($orderNo);
                
                // $order = Db::name("order")->where(['orderid' => $orderNo])->field("userid,zyid,ip,uopenid,orderid")->find();
                
                $userid = $order['userid'];
                
                
                $zyid = $order['zyid'];
                $ip = $order['ip'];
                $ddh = $orderNo;
                $qudao = $ddh;
                $ipz = Db::name("ip")->where(["ddh2" => $ddh])->find();
                if (!empty($ipz))
                {
                    echo "FAIL";
                    exit;
                }
                
                
                 if($order['order_type'] == 2){
                    Db::name('baotian')->insert(['userid' => $order['userid'],'zyid' => $order['zyid'],'money' => $order['money'],'uopenid' => $order['uopenid'],'create_time' => time(),'end_time' => time() + 86400,'orderid' => $orderNo]);
                }
                
                if(Cache::store('redis')->has($order['uopenid'])){

                    $zyidstr = Cache::store('redis')->get($order['uopenid']);
                  
                    $zyidstr = $zyidstr.','.$zyid;
                    
                    Cache::store('redis')->set($order['uopenid'],$zyidstr,604800);
                }else{
                    
                    Cache::store('redis')->set($order['uopenid'],$zyid,604800);
                   
                }
                Db::name("gongyou")->where(['id' => $zyid])->setInc("count"); 
                // Db::name("gongyou")->where(['id' => $zyid])->setInc("rcount");
                if (true)
                {
                    $kl = Db::name("kou")->where(['userid' => $userid])->find();
                    $ns = $kl['ns'];
                    if (!empty($kl))
                    {
                        $cs = $kl['cs'] - 1;
                        if ($cs <= 0)
                        {
                            $shipin = Cache::store('redis')->get('ylgongyou'.$zyid);
                            $zymc = $shipin['name'];
                            $user = Db::name("member")->where(['id' => $userid])->find();
                            $name = $user['nickname'];
                            $data = [];
                            $data['name'] = $name;
                            $data['userid'] = $userid;
                            $data['ddh'] = $ddh;
                            $data['qudao'] = $qudao;
                            $data['money'] = $cymoney;
                            $data['shijian'] = $shijian;
                            $data['zymc'] = $zymc;
                            $data['order_type'] = $order['order_type'];
                            Db::name("kl")->insert($data);
                            Db::name("kou")->where(['userid' => $userid])->update(['cs' => $ns]);
                            // 不扣量
                            // Db::name("siyou")->where(['id'=>$zyid])->setInc("cs");
                            //  Db::name("gongyou")->where(['id' => $shipin['pid']])->setInc("cs"); 
                            // // //
                            $ddh2 = substr($ddh, 0, 10);
                            $data = [];
                            $data['ip'] = $ip;
                            $data['userid'] = $userid;
                            $data['ddh'] = $ddh2;
                            $data['zyid'] = $zyid;
                            $data['ddh2'] = $ddh;
                            $data['zt'] = "已付";
                            $data['shijian'] = time();
                            $data['openid']  = $openid;
                            $data['order_type'] = $order['order_type'];
                            // $data['zftd']     = $order['zftd'];
                            $data['uopenid']  = $order['uopenid'];
                            $data['end_time']  = time() + 86400;
                           
                            Db::name("ip")->insert($data);
                        }
                        else
                        {
                            Db::name("kou")->where(['userid' => $userid])->setDec("cs"); 
                            // 写自己的数据库
                            $row = Db::name("dingdan")->where(['ddh' => $qudao])->find();
                            if (empty($row))
                            { 
                                // /更新会员金额
                                $user = Db::name("member")->where(['id' => $userid])->find();
                                if (!empty($user))
                                {
                                    if ($cymoney < 1)
                                    {
                                        $money2 = $cymoney;
                                    }
                                    else
                                    {
                                        $money2 = $cymoney - (($cymoney * $user['txfeilv']) / 100);
                                    }
                                    $money = $user['money'] + $money2;
                                    Db::name("member")->where(['id' => $userid])->update(['money' => $money]);
                                }
                                $shipin = Cache::store('redis')->get('ylgongyou'.$zyid);
                                $zymc = $shipin['name'];
                                // if (!empty($shipin))
                                // {
                                //     // Db::name("siyou")->where(['id' => $zyid])->setInc("cs");
                                //     Db::name("gongyou")->where(['id' => $shipin['pid']])->setInc("cs");
                                // }
                                $data = [];
                                $data['zyid'] = $zyid;
                                $data['userid'] = $userid;
                                $data['zymc'] = $zymc;
                                $data['ddh'] = $ddh;
                                $data['money'] = $cymoney;
                                $data['shijian'] = $shijian;
                                $data['wxddh'] = $weixin;
                                $data['order_type'] = $order['order_type'];
                                Db::name("dingdan")->insert($data);
                                $ddh2 = substr($ddh, 0, 10);
                                $data = [];
                                $data['ip'] = $ip;
                                $data['userid'] = $userid;
                                $data['ddh'] = $ddh2;
                                $data['zyid'] = $zyid;
                                $data['ddh2'] = $ddh;
                                $data['zt'] = "已付";
                                $data['shijian'] = time();
                                $data['openid']  = $openid;
                                // $data['zftd']     = $order['zftd'];
                                $data['uopenid']  = $order['uopenid'];
                                $data['end_time']  = time() + 86400;
                                $data['order_type'] = $order['order_type'];
                                Db::name("ip")->insert($data);
                            } 
                            // 写自己的数据库
                        } 
                        // 不扣量
                        // 代理ID没添加扣量参数
                    }
                    else
                    { 
                        // 写自己的数据库
                        $row = Db::name("dingdan")->where(['ddh' => $qudao])->find();
                        if (empty($row))
                        { 
                            // /更新会员金额
                            $user = Db::name("member")->where(['id' => $userid])->find();
                            if (!empty($user))
                            {
                                if ($cymoney < 1)
                                {
                                    $money2 = $cymoney;
                                }
                                else
                                {
                                    $money2 = $cymoney - (($cymoney * $user['txfeilv']) / 100);
                                }
                                $money = $user['money'] + $money2;
                                Db::name("member")->where(['id' => $userid])->update(['money' => $money]);
                            }
                            $shipin = Cache::store('redis')->get('ylgongyou'.$zyid);
                            $zymc = $shipin['name'];
                            
                            $data = [];
                            $data['zyid'] = $zyid;
                            $data['userid'] = $userid;
                            $data['zymc'] = $zymc;
                            $data['ddh'] = $ddh;
                            $data['money'] = $cymoney;
                            $data['shijian'] = $shijian;
                            $data['wxddh'] = $weixin;
                            $data['order_type'] = $order['order_type'];
                            Db::name("dingdan")->insert($data);
                            $ddh2 = substr($ddh, 0, 10);
                            $data = [];
                            $data['ip'] = $ip;
                            $data['userid'] = $userid;
                            $data['ddh'] = $ddh2;
                            $data['zyid'] = $zyid;
                            $data['ddh2'] = $ddh;
                            $data['zt'] = "已付";
                            $data['shijian'] = time();
                            $data['openid']  = $openid;
                            // $data['zftd']     = $order['zftd'];
                            $data['uopenid']  = $order['uopenid'];
                            $data['end_time']  = time() + 86400;
                            $data['order_type'] = $order['order_type'];
                            Db::name("ip")->insert($data);
                        } 
                        // 写自己的数据库
                    } 
                    // 代理ID没添加扣量参数
                    // 扣量开关关闭
                }
                else
                {
                    $row = Db::name("dingdan")->where(['ddh' => $qudao])->find();
                    if (empty($row))
                    { 
                        // /更新会员金额
                        $user = Db::name("member")->where(['id' => $userid])->find();
                        if (!empty($user))
                        {
                            if ($cymoney < 1)
                            {
                                $money2 = $cymoney;
                            }
                            else
                            {
                                $money2 = $cymoney - (($cymoney * $user['txfeilv']) / 100);
                            }
                            $money = $user['money'] + $money2;
                            Db::name("member")->where(['id' => $userid])->update(['money' => $money]);
                        }
                        $shipin = Cache::store('redis')->get('ylgongyou'.$zyid);
                        $zymc = $shipin['name'];
                       
                        $data = [];
                        $data['zyid'] = $zyid;
                        $data['userid'] = $userid;
                        $data['zymc'] = $zymc;
                        $data['ddh'] = $ddh;
                        $data['money'] = $cymoney;
                        $data['shijian'] = $shijian;
                        $data['wxddh'] = $weixin;
                        $data['order_type'] = $order['order_type'];
                        Db::name("dingdan")->insert($data);
                        $ddh2 = substr($ddh, 0, 10);
                        $data = [];
                        $data['ip'] = $ip;
                        $data['userid'] = $userid;
                        $data['ddh'] = $ddh2;
                        $data['zyid'] = $zyid;
                        $data['ddh2'] = $ddh;
                        $data['zt'] = "已付";
                        $data['shijian'] = time();
                        $data['openid']  = $openid;
                        // $data['zftd']     = $order['zftd'];
                        $data['uopenid']  = $order['uopenid'];
                        $data['end_time']  = time() + 86400;
                        $data['order_type'] = $order['order_type'];
                        Db::name("ip")->insert($data);
                    } 
                    // 写自己的数据库
                }
            
		      return '<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>';

                // 扣量开关关闭
            }
            
            
            
            
            
            
            
        }
    }
    
  
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
}
